package com.shunhao.mvvm

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.HashMap

/**
 * @author Administrator
 */
open class BaseViewModel(application: Application) : AndroidViewModel(application), IBaseViewModel,
    Consumer<Disposable?> {

    private var mCompositeDisposable: CompositeDisposable? = null

    protected fun addDisposable(disposable: Disposable?) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = CompositeDisposable()
        }
        if (disposable != null) {
            mCompositeDisposable?.add(disposable)
        }
    }

    override fun onCleared() {
        super.onCleared()
        if (mCompositeDisposable != null && !mCompositeDisposable?.isDisposed!!) {
            mCompositeDisposable?.clear()
        }
    }

    override fun onAny(owner: LifecycleOwner?, event: Lifecycle.Event?) {}
    override fun onCreate() {}
    override fun onDestroy() {}
    override fun onStart() {}
    override fun onStop() {}
    override fun onResume() {}
    override fun onPause() {}

    @Throws(Exception::class)
    override fun accept(disposable: Disposable?) {
        addDisposable(disposable)
    }

    fun getRequestBody2Json(commitHashMap: HashMap<String, Any>): RequestBody {
        val json = GsonUtils.toJson(commitHashMap)
        return json.toRequestBody("application/json".toMediaType())
    }

    fun parseRequestBody(value: String): RequestBody {
        return value.toRequestBody("text/plain".toMediaType())
    }
}